<?php
namespace Common\Util;

vendor('AlibabaCloud.autoload');
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Services\User\UserService;
use think\Db;
use Think\Upload\Driver\Qiniu\QiniuStorage;

class BaseData{

	/**
	 * 获取系统设置
	 */
	public static function getAppSetting($is_api = false){
		$app_system_setting = S('app_system_setting_data_v1');
		if(!$app_system_setting){
			$app_system_setting = [];
			$t_app_setting = M("app_setting");
			$setting_list = $t_app_setting->select();
			foreach($setting_list as $key => $val){
				$app_system_setting[$val['name']] = $val['value'];
			}
			S('app_system_setting_data', $app_system_setting);
		}
		if($is_api == true){
			unset($app_system_setting['wx_app_appid']);
			unset($app_system_setting['wx_app_appsecret']);
			unset($app_system_setting['wx_app_gid']);
			unset($app_system_setting['wx_app_name']);
			unset($app_system_setting['wechat_name']);
			unset($app_system_setting['wechat_gid']);
			unset($app_system_setting['wechat_no']);
			unset($app_system_setting['wechat_rcode']);
			unset($app_system_setting['wechat_appid']);
			unset($app_system_setting['wechat_appsecret']);
			unset($app_system_setting['wechat_type']);
			unset($app_system_setting['wepay_shanghuhao']);
			unset($app_system_setting['wepay_partnerkey']);
			unset($app_system_setting['wepay_cert_pem']);
			unset($app_system_setting['wepay_key_pem']);
			unset($app_system_setting['qiniu_domain']);
			unset($app_system_setting['qiniu_bucket']);
			unset($app_system_setting['qiniu_accesskey']);
			unset($app_system_setting['qiniu_secretkey']);
			unset($app_system_setting['api_qq_map_key']);
		}
		return $app_system_setting;
	}

	/**
	 * 获取用户信息
	 *
	 * @param $user_id
	 * @return array|mixed
	 */
	public static function getUserInfoByToken($user_token){
		$t_user = M("user");
		$user_info = $t_user->where(['token' => $user_token])->find();
		if($user_info){
			$user_info['user_headimg'] = $user_info['user_headimg'] ? $user_info['user_headimg'] : "http://xcx.tfxiaochengxu.com/2018-06-15_5b235fa500726.png";
		}
        if ($user_info) {
            $user_info['card_info'] = (new UserService())->card($user_info['id']);
        }
        return $user_info ? $user_info : [];
	}

    /**
     * 发送模版消息(废弃)
     * @param $send_user_id
     * @param $view_number
     * @deprecated
     * @return bool
     */
	public static function sendMessage($send_user_id = 0, $view_number = 0){
		$appSetting = self::getAppSetting(true);
		//订单信息
		$user_info = M('user')->find($send_user_id);
		$openid = $user_info['user_openid'];
		$data = [
			'touser'      => $openid,
			'template_id' => 'NHhKuayLQlV2sDBb2uwIwcrNzNeu5GeXR-puCSp2vA8',
			'url'         => $appSetting['beiyong_app_domain'].'/h5app/pages/track/track',
			'data'        => [],
		];
		//	访客名称
		$data['data']['thing1'] = ['value' => '有客来访', 'color' => "#fc0101"];
		//		访问次数
		$data['data']['character_string14'] = ['value' => $view_number, 'color' => "#173177"];
		$get_access_token = get_access_token();
		$json_data = json_encode($data, JSON_UNESCAPED_UNICODE);//转化成json数组让微信可以接收
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$get_access_token;//模板消息请求URL

        $res = https_request($url, $json_data);//请求开始
		$res = json_decode($res, true);
		if($res['errcode'] == 0 && $res['errcode'] == "ok"){
			//			更新提醒消息状态
			M("user_view_log")->where(['user_id' => $user_info['view_user_id']])->save([
				'is_tip'   => 1,
				'tip_time' => time(),
			]);
			//判断用户需要多久提醒一次
			if($user_info['view_log_tip_type'] == 2){
				$save['log_tip_time'] = strtotime("+15 minutes", time());
			}elseif($user_info['view_log_tip_type'] == 3){
				$save['log_tip_time'] = strtotime('+1 hour', time());
			}elseif($user_info['view_log_tip_type'] == 4){
				$save['log_tip_time'] = strtotime('+3 hour', time());
			}else{
				$save['log_tip_time'] = 0;
			}
			$save['is_tip'] = 1;
			M("user_view_log")->where(['user_id' => $user_info['view_user_id']])->save($save);
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 获取轮播图
	 *
	 * @param int   $cate_id
	 * @param int   $num
	 * @param array $map
	 * @return null
	 */
	public static function getAdList($cate_id = 0, $num = 10, $map = []){
		$t_cms_ad = M("cms_ad");
		if($cate_id > 0){
			$map['cate_id'] = $cate_id;
		}
		$map['is_show'] = 1;
		$list = $t_cms_ad->where($map)->limit($num)->order("`is_order` Asc,`id` Asc")->select();
		foreach($list as $key => $val){
			$list[$key]['cover'] = get_cover_img($val['cover']);
		}
		return $list ? $list : [];
	}

	/**
	 * 获取乐观锁信息
	 *
	 * @return mixed
	 */
	public static function getTaskLockInfo(){
		$t_task_lock = M("task_lock");
		if(!$task_lock_info = $t_task_lock->order("id Asc")->find()){
			$info['this_time'] = time();
			$info['version'] = 1;
			$insert_id = $t_task_lock->add($info);
			$info['id'] = $insert_id;
			return $info;
		}
		return $task_lock_info;
	}

	/**
	 * 获取提现乐观锁信息
	 *
	 * @return mixed
	 */
	public static function getCashTaskLockInfo(){
		$t_task_lock_cash = M("task_lock_cash");
		if(!$task_lock_info = $t_task_lock_cash->order("id Asc")->find()){
			$info['this_time'] = time();
			$info['version'] = 1;
			$insert_id = $t_task_lock_cash->add($info);
			$info['id'] = $insert_id;
			return $info;
		}
		return $task_lock_info;
	}

	/**
	 * 获取当前域或
	 *
	 * @return string
	 */
	public static function getThisUrl(){
		return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
	}

	/**
	 * 获取QQMap随机key
	 */
	public static function getQQMapRandKey(){
		$app_config = self::getAppSetting();
		$api_qq_map_key = $app_config['api_qq_map_key'];
		if(empty($api_qq_map_key)){
			return '';
		}
		$api_qq_map_key_data = explode("\n", $api_qq_map_key);
		$data_length = count($api_qq_map_key_data);
		$rand_num = mt_rand(0, ($data_length - 1));
		return $api_qq_map_key_data[$rand_num];
	}

	/**
	 * 阿里云短信发送
	 */
	public static function AlibabaCloudSendSms($phone, $template_id, $param_data){
		$app_config = self::getAppSetting();
		AlibabaCloud::accessKeyClient($app_config['aliyun_sms_accesskey'], $app_config['aliyun_sms_accesssecret'])
			->regionId('cn-hangzhou')
			->asDefaultClient();
		if(is_array($param_data)) $param_data = json_encode($param_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
		try{
			$result = AlibabaCloud::rpc()
				->product('Dysmsapi')
				// ->scheme('https') // https | http
				->version('2017-05-25')
				->action('SendSms')
				->method('POST')
				->options([
					'query' => [
						'RegionId'      => $app_config['aliyun_sms_regionid'] ? $app_config['aliyun_sms_regionid'] : '',
						'PhoneNumbers'  => $phone,
						'SignName'      => $app_config['aliyun_sms_signname'],
						'TemplateCode'  => $template_id,
						'TemplateParam' => $param_data,
					],
				])
				->request();
			return ['code' => 1, 'info' => $result->toArray()];
		}catch(ClientException $e){
			return ['code' => 0, 'info' => $e->getErrorMessage()];
		}catch(ServerException $e){
			return ['code' => 0, 'info' => $e->getErrorMessage()];
		}
	}

	/**
	 * 短信宝发送验证码
	 *
	 * @param $phone
	 * @param $content
	 * @return array
	 */
	public static function SmsbaoSendSms($phone, $content){
		$app_config = self::getAppSetting();
		$statusStr = [
			"0"  => "短信发送成功",
			"-1" => "参数不全",
			"-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
			"30" => "短信平台密码错误",
			"40" => "短信平台账号不存在",
			"41" => "短信平台余额不足",
			"42" => "帐户已过期",
			"43" => "IP地址限制",
			"50" => "内容含有敏感词",
		];
		$smsapi = "https://api.smsbao.com/";
		$user = $app_config['smsbao_user_name'];
		$pass = md5($app_config['smsbao_user_pass']);
		$sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
		$result = file_get_contents($sendurl);
		return ['code' => $result, 'info' => $statusStr[$result]];
	}

	/**
	 * 上传七牛远程链接或资源
	 *
	 * @param      $key  文件名
	 * @param      $data 文件路径或资源
	 * @param bool $is_source
	 * @return string
	 */
	public static function uploadStaticFile($key, $data, $is_source = false){
		$app_config = self::getAppSetting();
		$qc_config = [
			'accessKey' => $app_config['storage_qiniu_access_key'],
			'secretKey' => $app_config['storage_qiniu_secret_key'],
			'bucket'    => $app_config['storage_qiniu_bucket'],
			'domain'    => $app_config['storage_qiniu_domain'],
			'timeout'   => 3600,
		];
		$qiniu_upload = new QiniuStorage($qc_config);
		if($is_source == false){
			$source_data = file_get_contents($data);
		}else{
			$source_data = $data;
		}
		$upfile = [
			'name'     => 'file',
			'fileName' => $key,
			'fileBody' => $source_data,
		];
		dump($qc_config);
		exit();

		$result = $qiniu_upload->upload([], $upfile);
		if(false === $result){
			return false;
		}else{
			$url = $qiniu_upload->downlink($key);
			return $url;
		}
	}

	public static function getGoodsDanweiData(){
		$t_goods_danwei = M('goods_danwei');
		$list = $t_goods_danwei->field('name')->order("is_order Asc,id Asc")->select();
		$data = [];
		foreach($list as $item){
			$data[] = $item['name'];
		}
		return $data;
	}

	/**
	 * 生成二维码
	 *
	 * @param string $text
	 * @param string $logo
	 * @return mixed
	 */
	public static function makeQrcode($text = '', $logo = ''){
		$liantu_api_url = "http://qr.liantu.com/api.php?text=".$text;
		if(!empty($logo)){
			$liantu_api_url .= '&logo='.$logo;
		}
		return cyz_curl_get_contents($liantu_api_url);
	}

	/**
	 * 生成商品编码
	 *
	 * @return string
	 */
	public static function makeNewGoodsSn(){
		$t_goods = M("goods");
		if($last_goods_info = $t_goods->order("id Desc")->find()){
			$last_goods_sn = $last_goods_info['goods_sn'];
			$last_goods_sn_date = substr($last_goods_sn, 2, 8);
			$last_goods_sn_num = substr($last_goods_sn, 10, 4);
			if($last_goods_sn_date == date("Ymd")){
				$new_goods_sn_num = $last_goods_sn_num + 1;
				if($new_goods_sn_num < 10){
					$new_goods_sn_num = '000'.$new_goods_sn_num;
				}elseif($new_goods_sn_num >= 10 && $new_goods_sn_num < 100){
					$new_goods_sn_num = '00'.$new_goods_sn_num;
				}elseif($new_goods_sn_num >= 100 && $new_goods_sn_num < 1000){
					$new_goods_sn_num = '0'.$new_goods_sn_num;
				}
				return 'SP'.date("Ymd").$new_goods_sn_num;
			}else{
				return 'SP'.date("Ymd").'0000';
			}
		}
		return 'SP'.date("Ymd").'0000';
	}

	/**
	 * 生成入库单编码
	 *
	 * @return string
	 */
	public static function makeInStorageSn(){
		$t_stock_in_storage = M("stock_in_storage");
		if($last_storage_info = $t_stock_in_storage->order("id Desc")->find()){
			$last_business_sn = $last_storage_info['business_sn'];
			$last_business_sn_date = substr($last_business_sn, 2, 8);
			$last_business_sn_num = substr($last_business_sn, 10, 4);
			if($last_business_sn_date == date("Ymd")){
				$new_business_sn_num = $last_business_sn_num + 1;
				if($new_business_sn_num < 10){
					$new_business_sn_num = '000'.$new_business_sn_num;
				}elseif($new_business_sn_num >= 10 && $new_business_sn_num < 100){
					$new_business_sn_num = '00'.$new_business_sn_num;
				}elseif($new_business_sn_num >= 100 && $new_business_sn_num < 1000){
					$new_business_sn_num = '0'.$new_business_sn_num;
				}
				return 'RK'.date("Ymd").$new_business_sn_num;
			}else{
				return 'RK'.date("Ymd").'0000';
			}
		}
		return 'RK'.date("Ymd").'0000';
	}

	/**
	 * 生成出库单编码
	 *
	 * @return string
	 */
	public static function makeOutStorageSn(){
		$t_stock_out_storage = M("stock_out_storage");
		if($last_storage_info = $t_stock_out_storage->order("id Desc")->find()){
			$last_business_sn = $last_storage_info['business_sn'];
			$last_business_sn_date = substr($last_business_sn, 2, 8);
			$last_business_sn_num = substr($last_business_sn, 10, 4);
			if($last_business_sn_date == date("Ymd")){
				$new_business_sn_num = $last_business_sn_num + 1;
				if($new_business_sn_num < 10){
					$new_business_sn_num = '000'.$new_business_sn_num;
				}elseif($new_business_sn_num >= 10 && $new_business_sn_num < 100){
					$new_business_sn_num = '00'.$new_business_sn_num;
				}elseif($new_business_sn_num >= 100 && $new_business_sn_num < 1000){
					$new_business_sn_num = '0'.$new_business_sn_num;
				}
				return 'CK'.date("Ymd").$new_business_sn_num;
			}else{
				return 'CK'.date("Ymd").'0000';
			}
		}
		return 'CK'.date("Ymd").'0000';
	}

	/**
	 * 生成订单号
	 *
	 * @param string $prefix
	 * @return string
	 */
	public static function makeOrderSn($prefix = ''){
		$datetime = date('YmdHis');
		$microtime = explode(' ', microtime());
		$microtime = substr($microtime[0] ? $microtime[0] * 1000000000 : 1000000000, -6, 6);
		$randCode = substr(implode(null, array_map('ord', str_split(uniqid(), 1))), -8, 8);

		return $prefix.$datetime.$microtime.$randCode;
	}

	/**
	 * 获取区域数据
	 *
	 * @param $parent_id
	 * @return array
	 */
	public static function getRegionList($parent_id){
		$t_region = M("RegionList");
		$parent_id = intval($parent_id);
		$map['parent_id'] = $parent_id;
		$c_list = $t_region->where($map)->field("region_name,parent_id,region_level,id")->order("id Asc")->cache(true)->select();
		if($c_list){
			foreach($c_list as $key => $val){
				$c_list[$key]['region_id'] = $val['id'];
				$c_list[$key]['region_level'] = $val['region_level'];
				$c_list[$key]['is_select'] = false;
			}
			return $c_list;
		}else{
			return [];
		}
	}

	/**
	 * 获取区域数据详情
	 *
	 * @param int $region_id
	 * @return bool|mixed
	 */
	public static function getRegionInfo($region_id = 0){
		$t_region = M("RegionList");
		$region_id = intval($region_id);
		$map['id'] = $region_id;
		if($region_info = $t_region->where($map)->find()){
			return $region_info;
		}
		return false;
	}

	/**
	 * 记录要处理日志
	 *
	 * @param $content
	 */
	public static function addErrorLogData($content){
		$t_action_error_log = M("action_error_log");
		$a_data['error_content'] = $content ? $content : '';
		$a_data['is_do'] = 0;
		$a_data['add_time'] = time();
		$t_action_error_log->add($a_data);
	}
}
